package api

import (
	"awesomeProject2/global"
	"awesomeProject2/middleware"
	"awesomeProject2/model"
	"awesomeProject2/model/request"
	"awesomeProject2/model/response"
	"awesomeProject2/service"
	"github.com/gin-gonic/gin"
	"go.uber.org/zap"
)

func Login(c *gin.Context) {
	var l request.Login

	if err := c.ShouldBindJSON(&l); err != nil {
		response.FailWithError(err, c)
		return
	}

	u := &model.User{Username: l.Username, Password: l.Password}

	if err, user := service.Login(u); err != nil {
		global.GVA_LOG.Error("登陆失败!", zap.Any("err", err))
		response.FailWithError(err, c)
	} else {
		tokenString, _ := middleware.GetToken(user.ID)
		response.OkWithData(response.LoginResponse{
			IsAdmin: user.IsAdmin,
			Token:   tokenString}, c)
	}
}

func ChangePasswd(c *gin.Context) {
	var newPwd request.PassWord

	id, _ := c.Get("userid")

	if err := c.ShouldBindJSON(&newPwd); err != nil {
		response.FailWithError(err, c)
		return
	}

	if err := service.ChangePasswd(id.(uint), newPwd.PassWord); err != nil {
		response.Fail(c)
	} else {
		response.Ok(c)
	}
}
